<template>
  <div class="process-panel__container" :style="{ width: `${width}px` }">
    <el-collapse v-model="activeTab">
      <el-collapse-item name="base">
        <!-- class="panel-tab__title" -->
        <template #title>
          基本信息
        </template>
        <ElementBaseInfo
            :id-edit-disabled="idEditDisabled"
            :business-object="elementBusinessObject"
            :type="elementType"
        />
      </el-collapse-item>
      <el-collapse-item name="condition" v-if="conditionFormVisible" key="condition">
        <template #title>
          流转条件
        </template>
        <flow-condition :business-object="elementBusinessObject" :type="elementType"/>
      </el-collapse-item>
      <!--      <el-collapse-item name="condition" v-if="elementType === 'Process'" key="message">
              <template #title>
                <Icon icon="ep:comment"/>
                消息与信号
              </template>
              <signal-and-massage/>
            </el-collapse-item>

            <el-collapse-item name="condition" v-if="formVisible" key="form">
              <template #title>
                <Icon icon="ep:list"/>
                表单
              </template>
              <element-form :id="elementId" :type="elementType"/>
            </el-collapse-item>-->
      <el-collapse-item name="task" v-if="elementType.indexOf('Task') !== -1" key="task">
        <template #title>
          任务配置
        </template>
        <element-task :id="elementId" :type="elementType"/>
      </el-collapse-item>
      <el-collapse-item
          name="multiInstance"
          v-if="(elementType.indexOf('Task') !== -1 || elementType.indexOf('SubProcess') !== -1)"
          key="multiInstance"
      >
        <template #title>
          多实例配置
        </template>
        <element-multi-instance :business-object="elementBusinessObject" :type="elementType"/>
      </el-collapse-item>
      <!--<el-collapse-item name="listeners" key="listeners">
        <template #title>
          <Icon icon="ep:bell-filled"/>
          执行监听器
        </template>
        <element-listeners :id="elementId" :type="elementType"/>
      </el-collapse-item>
      <el-collapse-item name="taskListeners" v-if="elementType === 'UserTask'" key="taskListeners">
        <template #title>
          <Icon icon="ep:bell-filled"/>
          任务监听器
        </template>
        <user-task-listeners :id="elementId" :type="elementType"/>
      </el-collapse-item>
      <el-collapse-item name="extensions" key="extensions">
        <template #title>
          <Icon icon="ep:circle-plus-filled"/>
          扩展属性
        </template>
        <element-properties :id="elementId" :type="elementType"/>
      </el-collapse-item>
      <el-collapse-item name="other" key="other">
        <template #title>
          <Icon icon="ep:promotion"/>
          其他
        </template>
        <element-other-config :id="elementId"/>
      </el-collapse-item>-->
    </el-collapse>
  </div>
</template>
<script lang="ts" setup>
import {ref, provide, watch, onBeforeUnmount} from 'vue';
import ElementBaseInfo from '@/components/bpmn/penal/base/ElementBaseInfo'
import ElementTask from '@/components/bpmn/penal/task/ElementTask'
import ElementMultiInstance from '@/components/bpmn/penal/multi-instance/ElementMultiInstance'
import FlowCondition from '@/components/bpmn/penal/flow-condition/FlowCondition'

/*import ElementOtherConfig from '@/components/bpmn/penal/other/ElementOtherConfig'
import SignalAndMassage from '@/components/bpmn/penal/signal-message/SignalAndMessage'
import ElementListeners from '@/components/bpmn/penal/listeners/ElementListeners'
import ElementProperties from '@/components/bpmn/penal/properties/ElementProperties'
import UserTaskListeners from '@/components/bpmn/penal/listeners/UserTaskListeners'*/

defineOptions({name: 'MyPropertiesPanel'})

const props = defineProps({
  bpmnModeler: {
    type: Object,
    default: () => {
    }
  },
  engine: {
    type: String,
    default: 'camunda'
  },
  width: {
    type: Number,
    default: 480
  },
  idEditDisabled: {
    type: Boolean,
    default: false
  },
  model: Object // 流程模型的数据
})

const activeTab = ref(['base', 'task'])
const elementId = ref('')
const elementType = ref('')
const elementBusinessObject = ref<any>({}) // 元素 businessObject 镜像，提供给需要做判断的组件使用
const conditionFormVisible = ref(false) // 流转条件设置
const formVisible = ref(false) // 表单配置
const bpmnElement = ref()

provide('engine', props.engine)
provide('width', props.width)
const bpmnInstances = () => (window as any)?.bpmnInstances

// 监听 props.bpmnModeler 然后 initModels
const unwatchBpmn = watch(
    () => props.bpmnModeler,
    () => {
      // 避免加载时 流程图 并未加载完成
      if (!props.bpmnModeler) {
        return
      }

      const w = window as any
      w.bpmnInstances = {
        engine: props.engine,
        modeler: props.bpmnModeler,
        modeling: props.bpmnModeler.get('modeling'),
        moddle: props.bpmnModeler.get('moddle'),
        eventBus: props.bpmnModeler.get('eventBus'),
        bpmnFactory: props.bpmnModeler.get('bpmnFactory'),
        elementFactory: props.bpmnModeler.get('elementFactory'),
        elementRegistry: props.bpmnModeler.get('elementRegistry'),
        replace: props.bpmnModeler.get('replace'),
        selection: props.bpmnModeler.get('selection')
      }

      console.log(bpmnInstances(), 'window.bpmnInstances')
      getActiveElement()
      unwatchBpmn()
    },
    {
      immediate: true
    }
)

const getActiveElement = () => {
  // 初始第一个选中元素 bpmn:Process
  initFormOnChanged(null)
  props.bpmnModeler.on('import.done', (e) => {
    initFormOnChanged(null)
  })
  // 监听选择事件，修改当前激活的元素以及表单
  props.bpmnModeler.on('selection.changed', ({newSelection}) => {
    initFormOnChanged(newSelection[0] || null)
  })
  props.bpmnModeler.on('element.changed', ({element}) => {
    // 保证 修改 "默认流转路径" 类似需要修改多个元素的事件发生的时候，更新表单的元素与原选中元素不一致。
    if (element && element.id === elementId.value) {
      initFormOnChanged(element)
    }
  })
}
// 初始化数据
const initFormOnChanged = (element) => {
  let activatedElement = element
  if (!activatedElement) {
    activatedElement =
        bpmnInstances().elementRegistry.find((el) => el.type === 'bpmn:Process') ??
        bpmnInstances().elementRegistry.find((el) => el.type === 'bpmn:Collaboration')
  }
  if (!activatedElement) return
  bpmnInstances().bpmnElement = activatedElement
  bpmnElement.value = activatedElement
  elementId.value = activatedElement.id
  elementType.value = activatedElement.type.split(':')[1] || ''
  elementBusinessObject.value = JSON.parse(JSON.stringify(activatedElement.businessObject))
  conditionFormVisible.value = (
      elementType.value === 'SequenceFlow' &&
      activatedElement.source.type &&
      activatedElement.source.type.indexOf('Gateway') !== -1 &&
      activatedElement.source.type.indexOf('StartEvent') === -1
  )
  formVisible.value = elementType.value === 'UserTask' || elementType.value === 'StartEvent'
}

onBeforeUnmount(() => {
  const w = window as any
  w.bpmnInstances = null
})

</script>
<style lang="scss">
.process-panel {
  position: absolute;
  top: 20px;
  right: 10px;
  max-height: calc(100vh - 200px);
  overflow: auto;
  padding: 0 8px;
  background: hsl(225, 10%, 97%);
  border: solid 1px hsl(225, 10%, 75%);
  border-radius: 2px;
}

.el-collapse-item__wrap {
  background-color: unset !important;
}

.el-collapse-item__header {
  background-color: unset !important;
}
</style>